﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Musicman.Common.Entities;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using Musicman.Business;

namespace MusicmanWeb.Custom
{
    public partial class UserMessageControl : System.Web.UI.UserControl
    {
        private UserMessage message;
        private const int commentCount = 5;

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        
        public UserMessage Message
        {
            get { return message; }
            set 
            { 
                message = value;
                MessageID = message.MessageID;
                DisplayMessage();
            }
        }

        public long MessageID
        {
            get { object o = ViewState["MessageID"];
                    if (o == null)
                        return -1;
                    return (long)o;
            }
            set
            {
                ViewState["MessageID"] = value;
            }
        }

        // PROPERTY:: AutoGenerateCheckBoxColumn
        [Category("Behavior")]
        [Description("Whether all comments are displayed")]
        [DefaultValue(false)]
        public bool Expanded
        {
            get
            {
                object o = ViewState["Expanded"];
                if (o == null)
                    return false;
                return (bool)o;
            }
            set { ViewState["Expanded"] = value; }
        }

        protected void Expandlink_Command(object sender, CommandEventArgs e)
        {
            this.Expanded = !this.Expanded;
        }

        private void DisplayMessage()
        {
            this.profileImg.Src = "ProfilePicture.axd?personid=" + message.Sender.Personid;
            this.msgsender.InnerText = message.Sender.Firstname + " " + message.Sender.Lastname;
            this.msgtime.InnerText = String.Format("[{0}]", message.MessageDate.ToString("dd-MM-yyyy hh:mm"));
            this.msgcnt.InnerText = message.Message;
            deleteButton.CommandArgument = message.MessageID.ToString();
            deleteButton.Visible = (Page.User.Identity.Name == message.Sender.Personid.ToString());

            if (message.Commments != null)
            {
                DisplayComments(message);
            }

            Expandlink.CommandArgument = message.MessageID.ToString();
            CommentBtn.CommandArgument = message.MessageID.ToString();
            bool showExpand = (message.Commments != null && message.Commments.Count > commentCount);
            Expandlink.Visible = showExpand;
        }

        private void DisplayComments(UserMessage msg)
        {
            int firstMsgIndex = 0;
            int lastMsgIndex = msg.Commments.Count;
            if (!Expanded)
            {
                firstMsgIndex = lastMsgIndex - commentCount;

                if (firstMsgIndex < 0)
                    firstMsgIndex = 0;
            }
            UserMessage[] comments = new UserMessage[lastMsgIndex - firstMsgIndex];
            msg.Commments.CopyTo(firstMsgIndex, comments, 0, lastMsgIndex - firstMsgIndex);
            commentsrepeater.DataSource = comments;
            commentsrepeater.DataBind();
        }

        protected void commentsrepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteComment")
            {
                UserMessage parentMsg = null;
                List<UserMessage> messages = Cache["messages"] as List<UserMessage>;
                if (messages != null)
                {
                    parentMsg = messages.Find(delegate(UserMessage m) { return m.MessageID == this.MessageID; });
                }
                if (parentMsg != null && parentMsg.Commments != null)
                {
                    DisplayComments(parentMsg);
                }
            }
        }

        protected void Commentsrepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            UserMessage comment = e.Item.DataItem as UserMessage;
            MessageTemplateControl ctrl = (MessageTemplateControl)e.Item.FindControl("commentcontrol");
            if (comment != null)
            {
                ctrl.Message = comment;
            }
        }

        protected void Comment_Command(object sender, CommandEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.commenttxt.Value.Trim()))
            {
                long messageID = Int64.Parse(e.CommandArgument.ToString());
                UserMessage parent = null;
                List<UserMessage> messages = Cache["messages"] as List<UserMessage>;
                if (messages != null)
                {
                    parent = messages.Find(delegate(UserMessage msg) { return msg.MessageID == messageID; });
                }
                if (parent == null)
                {
                    // parent = getMessage()
                }
                User msgSender = UserManager.Instance.GetUser(Int64.Parse(Page.User.Identity.Name));
                UserMessage message = new UserMessage();
                message.MessageDate = DateTime.Now;
                message.Parent = parent;
                message.Message = this.commenttxt.Value.Trim();
                message.Sender = msgSender;
                if (UserMassageManager.Instance.InsertMessage(message))
                {
                    if (parent.Commments == null)
                    {
                        parent.Commments = new List<UserMessage>();
                    }
                    parent.Commments.Add(message);
                }
            }
        }

        protected void Delete_Command(object sender, CommandEventArgs e)
        {
            long messageID = Int64.Parse(e.CommandArgument.ToString());
            UserMassageManager.Instance.DeleteMessage(messageID);
            List<UserMessage> messages = Cache["messages"] as List<UserMessage>;
            UserMessage msg = null;
            if (messages != null)
            {
                msg = messages.Find(delegate(UserMessage m) { return m.MessageID == messageID; });
            }
            if (msg != null)
            {
                messages.Remove(msg);
            }
        }
     }
}